﻿
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;

using MTP.Core;
using MTP.Core.Remote;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace Microsoft.Extensions.DependencyInjection
{
    public static class MtpServicesExtensions
    {

        /// <summary>
        /// 自动注入
        /// </summary>
        /// <param name="services"></param>
        /// <param name="typeInfo"></param>
        private static Type GetInterfaces(TypeInfo typeInfo)
        {
            var interfaces = typeInfo.GetInterfaces();
            return typeInfo.GetInterfaces().FirstOrDefault(a => typeInfo.Name.Contains(a.Name.TrimStart('I'))) ?? typeInfo;
        }
  

        public static IServiceCollection AddMtp(this IServiceCollection services)
        {
            List<Type> types = MTPCoreUtil.FindTypeByAttribute<MtpServiceAttribute>()
                 .Select(typeInfo => GetInterfaces(typeInfo))
                 .ToList();
            return services 
                .Configure<MtpOptions>(options => options.AddRangeServices(types))
                .AddHostedService<MtpCoreService>();
        }

        public static IServiceCollection AddMtp(this IServiceCollection services, Action<MtpOptions> options)
        {
            return AddMtp(services).Configure(options);
        }

   
    }
}
